package com.sky.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.IDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜品 服务实现类
 * </p>
 *
 * @author fcy
 * @since 2025-09-08
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {

    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    public void add(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        this.save(dish);
        Long dishId = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null){
            flavors.forEach(flavor->{
                flavor.setDishId(dishId);
                dishFlavorMapper.insert(flavor);
            });
        }
    }
    /**
     * 菜品分页查询
     * @param pageDto
     * @return
     */
    @Override
    public Result<PageResult> getPage(DishPageQueryDTO pageDto) {
        //1.构建分页对象
        Page<Dish> page=new Page<>(pageDto.getPage(),pageDto.getPageSize());
        //2.构建查询条件
       lambdaQuery()
                .like(pageDto.getName()!=null,Dish::getName, pageDto.getName())
                .eq(pageDto.getCategoryId()!=null ,Dish::getCategoryId, pageDto.getCategoryId())
                .eq(pageDto.getStatus()!=null,Dish::getStatus, pageDto.getStatus())
                .page(page);
       List<DishVO> voList =new ArrayList<>();
       page.getRecords().forEach(dish -> {
           DishVO dishVO = new DishVO();
           BeanUtils.copyProperties(dish,dishVO);
           dishVO.setCategoryName(categoryMapper.selectById(dish.getCategoryId()).getName());
           voList.add(dishVO);
       });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(voList);
        return Result.success(pageResult);
    }
    /**
     * 菜品状态变更
     * @param
     * @return
     */
    @Override
    public Result<String> change(DishDTO dishDTO) {
        Dish dish = this.getById(dishDTO.getId());
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        this.updateById(dish);
        Long dishId = dish.getId();
        QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dish_id",dishId);
        dishFlavorMapper.delete(queryWrapper);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null){
            flavors.forEach(flavor->{
                flavor.setDishId(dishId);
                dishFlavorMapper.insert(flavor);
            });
        }
        return Result.success();

    }
    /**
     * 菜品查询
     * @param id
     * @return
     */
    @Override
    public Result<DishVO> selectById(Long id) {
        Dish res = this.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(res,dishVO);
        return Result.success(dishVO);
    }
    /**
     * 菜品查询根据分类id
     * @param categoryId
     * @return
     */
    @Override
    public Result<List<Dish>> getList(Integer categoryId) {
        List<Dish> list = lambdaQuery()
                .eq(Dish::getCategoryId, categoryId)
                .list();
        return Result.success(list);
    }
    /**
     * 菜品停售、起售
     * @param status
     * @param id
     */
    @Override
    public void changeStatus(Integer status, Long id) {
        Dish dish = this.getById(id);
        dish.setStatus(status);
        this.updateById(dish);
    }
    /**
     * 批量菜品删除
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        ids.forEach(id->{
           if(this.getById(id).getStatus()==1){
               throw new RuntimeException("菜品正在售卖中，不能删除");
           }
        });
        dishMapper.deleteBatchIds(ids);
        dishFlavorMapper.delete(new QueryWrapper<DishFlavor>().in("dish_id",ids));
    }
    /**
     * 用户端菜品查询
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> getUserList(Integer categoryId) {
        List<Dish> list = lambdaQuery()
                .eq(Dish::getCategoryId, categoryId)
                .eq(Dish::getStatus,1)
                .list();
        List<DishVO> voList = new ArrayList<>();
        list.forEach(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish,dishVO);
            String name = categoryMapper.selectById(dish.getCategoryId()).getName();
            dishVO.setCategoryName( name);
            Long id = dish.getId();
            QueryWrapper<DishFlavor> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("dish_id",id);
            List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(queryWrapper);
            dishVO.setFlavors(dishFlavors);
            voList.add(dishVO);
        });
        return voList;
    }

}
